package com.cards_game.simple_ddz.handler;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cards_game.common.CommonUtils;
import com.cards_game.simple_ddz.bean.UserBean;
import com.cards_game.simple_ddz.service.LoginService;

/**
 * @author 郭国辉
 * 
 *     2017年6月20日下午4:23:45
 */
@Controller
public class LoginHandler {
	@Resource
	private LoginService ls;
	
	Log log=LogFactory.getLog(this.getClass());	
	
	@RequestMapping(value = "exit.do")
	public String exit(HttpServletRequest request, ModelMap modelMap){
		HttpSession session=request.getSession();
		if(session!=null){
			try {
				session.invalidate();
			} catch (IllegalStateException e) {
				log.error(CommonUtils.getExceptionMessage(e));
			}catch (Exception e) {
				log.error(CommonUtils.getExceptionMessage(e));
			}
		}
		return "redirect:/";
	}
	
	@RequestMapping(value = "login.do")
	public String login(HttpServletRequest request, ModelMap modelMap) {
		String userNum=request.getParameter("userNum");
		String password=request.getParameter("password");
		if(StringUtils.isNotEmpty(userNum)&&StringUtils.isNotEmpty(password)){
			UserBean ub = ls.login(userNum, password);
			if(ub!=null){
				HttpSession newSession=request.getSession();
				newSession.setAttribute("userBean", ub);

				ServletContext context=request.getServletContext();
				Object oldSession=context.getAttribute(userNum);
				
				if(oldSession!=null){
					HttpSession hs=(HttpSession) oldSession;
					try {
						if(hs!=newSession){
							hs.invalidate();
						}
					} catch (IllegalStateException e) {
						log.error(CommonUtils.getExceptionMessage(e));
					}catch (Exception e) {
						log.error("未知异常，请重新登录");
						log.error(CommonUtils.getExceptionMessage(e));
					}
				}
				context.setAttribute(userNum, newSession);
			}
		}
		return "redirect:/";
	}
}
